package com.handle.common.core.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IP地址工具类
 * @author zhangqing
 */
public class IPAddressUtils {
    private static final Logger log = LoggerFactory.getLogger(IPAddressUtils.class);

    public static final String IP_URL = "https://restapi.amap.com/v5/ip";

    public static final String KEY = "bdfe226f8a0faa1cb578452ab34a41b0";

    /**
     * 根据ip获取归属地
     * @param ip ip地址
     * @return 返回该ip所属归属地
     */
    public static String getRealAddress(String ip) {
        String address = "XX-XX";
        // 内网不查询
        if (CusAccessObjectUtil.internalIp(ip)) {
            return "内网IP";
        }

        String body = HttpUtil.createGet(IP_URL + "?key=" + KEY + "&type=4&ip=" + ip).execute().body();
        if (StringUtils.isEmpty(body)) {
            log.error("获取地理位置异常 {}", ip);
            return address;
        }
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Integer status = jsonObject.getInt("status");
        if(status.equals(1)){
            String country = jsonObject.getStr("country");
            String province = jsonObject.getStr("province");
            String city = jsonObject.getStr("city");
            return String.format("%s-%s-%s",country,province,city);
        }
        return address;
    }

    /**
     * 根据ip获取网络类型
     * @param ip ip地址
     * @return 网络
     */
    public static String getNetwork(String ip){
        String network="未知网络";
        if("127.0.0.1".equals(ip)){
            return network;
        }
        String body = HttpUtil.createGet(IP_URL + "?key=" + KEY + "&type=4&ip=" + ip).execute().body();
        if (StringUtils.isEmpty(body)) {
            log.error("获取网络类型异常 {}", ip);
            return network;
        }
        JSONObject jsonObject = JSONUtil.parseObj(body);
        Integer status = jsonObject.getInt("status");
        if(status.equals(1)){
            return jsonObject.getStr("isp");
        }
        return network;
    }
}
